package controller

import (
	"log"

	"github.com/cyfqyb/fiber_demo/common"
	"github.com/gofiber/fiber/v2"
)

// RouteInitializer 定义一个类型来存储每个控制器的路由初始化函数
type RouteInitializer func(app *fiber.App)

var initializers []RouteInitializer

// RegisterRoute 注册一个控制器的路由初始化函数
func RegisterRoute(initializer RouteInitializer) {
	initializers = append(initializers, initializer)
}

// InitController 初始化所有注册的路由
func InitController(app *fiber.App) {
	//进行路由重定向
	app.Get("/", func(ctx *fiber.Ctx) error {
		return ctx.Redirect("/admin")
	})
	for _, initializer := range initializers {
		initializer(app)
	}
	log.Printf("路由分组已初始化")
}

func Success(c *fiber.Ctx, data any) error {
	return c.JSON(common.Success(data))
}
func Fail(c *fiber.Ctx, msg string) error {
	return c.JSON(common.Fail[any](msg))
}

func HandleResponse(handler func(*fiber.Ctx) (interface{}, error)) fiber.Handler {
	return func(c *fiber.Ctx) error {
		data, err := handler(c)
		if err != nil {
			if e, ok := err.(*fiber.Error); ok {
				return c.Status(e.Code).JSON(fiber.Map{
					"error":   e.Message,
					"success": false,
					"data":    nil,
				})
			} else if e, ok := err.(error); ok {
				return c.Status(fiber.StatusOK).JSON(fiber.Map{
					"error":   e.Error(),
					"success": false,
					"data":    nil,
				})
			}
			return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
				"error":   "Internal Server Error",
				"data":    nil,
				"success": false,
			})
		}
		return c.Status(fiber.StatusOK).JSON(fiber.Map{
			"error":   "",
			"success": true,
			"data":    data,
		})
	}
}
